sap.ui.define([
    "sap/m/bbf41/Module/controller/BaseController",
    "sap/ui/model/json/JSONModel"
], function (BaseController, JSONModel) {
    "use strict";
    var oView,
        dp,
        oModel = new JSONModel(),
        sSelectedDate;
    return BaseController.extend("sap.m.bbf41.Module.controller.Assembly", {
        onInit: function () {
            var me = this;
            oView = this.getView();
            me.handleRefresh();
            //oView.setModel(oModel);
            //oView.byId('shift1').setHeaderSpan([2]);
            //oView.byId('shift2').setHeaderSpan([2]);

            //this.loadFoundryDataModel(function () {
            //    var oLegend = oView.byId('legend'),
            //        sLegendId = oLegend.getId();
            //    oView.$().find('#' + sLegendId).removeClass('hide');
            //});
            //dp = oView.byId('historyDatePicker');
            //dp.attachEvent('change', function (oEvent) {
            //    sSelectedDate = oEvent.getSource().getValue();
            //    me.handleRefresh();
            //});
            var oIconTabBar = oView.byId('IconTabBar');
            oIconTabBar.attachSelect(function () {
                me.handleRefresh();
            });
        },
        handleRefresh: function () {
            this.loadFoundryDataModel();
        },
        loadFoundryDataModel: function (cb) {
            var me = this,
                oShift1Table = oView.byId('shift1Table'),
                oShift2Table = oView.byId('shift2Table'),
                url = '/NEP/ALS/api/Assembly?time='+Date.now();
            var oMessageStripQ = oView.byId('messageStripQ'),
                oMessageStripP = oView.byId('messageStripP');
            oShift1Table.setBusy(true);
            oShift2Table.setBusy(true);
            oMessageStripQ.setBusy(true);
            oMessageStripP.setBusy(true);
            if (sSelectedDate) {
                url += '?date=' + sSelectedDate;
            }
            setTimeout(function () {
                jQuery.ajax({
                    url: url,
                    dataType: "json",
                    success: function (resp) {
                        var oData = me.buildTableData(resp);
                        oModel.setData(oData);
                        oModel.refresh(true);
                        oView.setModel(oModel);
                        cb && cb.call(null);
                    }.bind(this),
                    error: function () {
                        oShift1Table.setBusy(false);
                        oShift2Table.setBusy(false);
                        jQuery.sap.log.error("failed to load json");
                    },
                    complete: function () {
                        oShift1Table.setBusy(false);
                        oShift2Table.setBusy(false);
                        oMessageStripQ.setBusy(false);
                        oMessageStripP.setBusy(false);
                    }
                });
            }, 768);
        },
        onNavButtonPress: function () {
            this.getRouter().navTo('welcome');
        },
        handleDatePicker: function () {
            dp.$().find('.sapUiIcon').trigger('click');
        },
        dateHelper: function (oConfig, fixed) {
            var date = new Date(),
                yyyy = date.getFullYear(),
                m = date.getMonth();
            if (fixed === undefined) {
                m += 1;
            }
            var d = date.getDate(),
                paddingNum = function (n) {
                    if (n < 10) {
                        n = '0' + n;
                    }
                    return n;
                },
                MM = paddingNum(m),
                dd = paddingNum(d);
            var result = {
                yyyy: yyyy,
                MM: MM,
                dd: dd
            };
            if (oConfig) {
                var symbol = oConfig['symbol'] || '-';
                result = yyyy + symbol + MM + symbol + dd;
            }
            return result;
        },
        buildTableData: function (resp) {
            var data = {
                LineQRate: 0,
                LinePRate: 0,
                "Collection": [
                    {
                        "Type": "",
                        "Shift1LineQ": "Line Q",
                        "Shift1LineP": "Line P",
                        "Shift2LineQ": "Line Q",
                        "Shift2LineP": "Line P"
                    },
                    {
                        "Type": "Target",
                        "Shift1LineQ": 0,
                        "Shift1LineP": 0,
                        "Shift2LineQ": 0,
                        "Shift2LineP": 0
                    },
                    {
                        "Type": "Current",
                        "Shift1LineQ": 0,
                        "Shift1LineP": 0,
                        "Shift2LineQ": 0,
                        "Shift2LineP": 0
                    },
                    {
                        "Type": "Forecast",
                        "Shift1LineQ": 0,
                        "Shift1LineP": 0,
                        "Shift2LineQ": 0,
                        "Shift2LineP": 0
                    },
                    {
                        "Type": "Planned",
                        "Shift1LineQ": 0,
                        "Shift1LineP": 0,
                        "Shift2LineQ": 0,
                        "Shift2LineP": 0
                    }
                ],
                "Shift1StartTime": "06:00",
                "Shift1EndTime": "15:00",
                "pShift1StartTime": "06:00",
                "pShift1EndTime": "15:00",
                "Shift2StartTime": "15:00",
                "Shift2EndTime": "00:00",
                "pShift2StartTime": "15:00",
                "pShift2EndTime": "00:00",
                "Date": "yyyy-MM-dd",
                "Legend": {
                    "Red": "<p class=\"legend-label\"><span class=\"legend-block legend-red\"></span> current &lt; planned</p>",
                    "Green": "<p class=\"legend-label\"><span class=\"legend-block legend-green\"></span> current &gt;= planned</p>"
                }
            };
            data['Date'] = sSelectedDate || this.dateHelper(true);
            var po = data['Collection'];
            if (resp && resp['shifts_info']) {
                var so = resp['shifts_info'],
                    shiftNum = so['shift_num'];

                po[1]['Shift1LineQ'] = so['q_target_1'];
                po[1]['Shift2LineQ'] = so['q_target_2'];
                po[2]['Shift1LineQ'] = so['q_current_1'];
                po[3]['Shift1LineQ'] = so['q_forecast_1'];
                po[4]['Shift1LineQ'] = so['q_planned_1'];
                var weekNum = so['week_num'];
                if (weekNum % 2 == 1) {
                    po[1]['Shift1LineP'] = so['p_target_1'];
                    po[2]['Shift1LineP'] = so['p_current_1'];
                    po[3]['Shift1LineP'] = so['p_forecast_1'];
                    po[4]['Shift1LineP'] = so['p_planned_1'];
                    data['pShift2StartTime'] = '';
                    data['pShift2EndTime'] = '';
                    po[1]['Shift2LineP'] = '-';
                    po[2]['Shift2LineP'] = '-';
                    po[3]['Shift2LineP'] = '-';
                    po[4]['Shift2LineP'] = '-';
                }
                else {
                    data['pShift1StartTime'] = '';
                    data['pShift1EndTime'] = '';
                    po[1]['Shift1LineP'] = '-';
                    po[2]['Shift1LineP'] = '-';
                    po[3]['Shift1LineP'] = '-';
                    po[4]['Shift1LineP'] = '-';
                    po[1]['Shift2LineP'] = so['p_target_1'];
                    po[2]['Shift2LineP'] = so['p_current_1'];
                    po[3]['Shift2LineP'] = so['p_forecast_1'];
                    po[4]['Shift2LineP'] = so['p_planned_1'];
                }

                if (shiftNum == 1) {
                    po[2]['Shift2LineQ'] = '-';
                    po[3]['Shift2LineQ'] = '-';
                    po[4]['Shift2LineQ'] = '-';
                }
                else {
                    po[2]['Shift2LineQ'] = so['q_current_2'];
                    po[3]['Shift2LineQ'] = so['q_forecast_2'];
                    po[4]['Shift2LineQ'] = so['q_planned_2'];
                }
                this.calcLineRate(data, so);
            }
            return data;
        },
        calcLineRate: function (data, so) {
            var paddingNum = function (n) {
                    if (n < 10) {
                        n = '0' + n;
                    }
                    return n;
                },
                date = new Date(),
                y = date.getFullYear(),
                m = paddingNum(date.getMonth() + 1),
                d = paddingNum(date.getDate()),
                hh = paddingNum(date.getHours()),
                mm = paddingNum(date.getMinutes()),
                ss = paddingNum(date.getSeconds()),
                nowDateStr = y + '/' + m + '/' + d,
                nowTimeIntVal = parseInt(hh + '' + mm + '' + ss),
                weekNum = so['week_num'],
                qRate,
                pRate = 0,
                shiftNum = data['shiftNum'] || 0;
            var strToInt = function (str) {
                if (str) {
                    var ptn = new RegExp(':', 'g');
                    str = str.replace(ptn, '');
                }
                return parseInt(str);
            };
            var calcRate = function (total, sTime, eTime, lineName) {
                var ds = y + '/' + m + '/' + d + ' ' + sTime,
                    timeSec = (new Date(ds)).getTime() / 1000,
                    nowTimeSec = parseInt((new Date()).getTime() / 1000),
                    realNowTimeSec = nowTimeSec,
                    sTimeIntVal = strToInt(sTime),
                    eTimeIntVal = strToInt(eTime),
                    restSec = 0,
                    flag = true; // 当前时间是否为工作时间的标记位
                if (lineName == 'q') {
                    var lunchStartTime = '10:20:00',
                        dinnerStartTime = '18:20:00',
                        lunchStartIntVal = strToInt(lunchStartTime),
                        lunchEndIntVal = 110500,
                        dinnerStartIntVal = strToInt(dinnerStartTime),
                        dinnerEndIntVal = 190500;
                    if (nowTimeIntVal < sTimeIntVal) {
                        flag = false;
                    }
                    else if (nowTimeIntVal >= lunchStartIntVal && nowTimeIntVal < lunchEndIntVal) {
                        var restTimeStr = nowDateStr + ' ' + lunchStartTime;
                        var dt = new Date(restTimeStr);
                        nowTimeSec = parseInt(dt.getTime() / 1000);
                        restSec += realNowTimeSec - nowTimeSec;
                    }
                    else if(nowTimeIntVal >= dinnerStartIntVal && nowTimeIntVal < dinnerEndIntVal) {
                        var restTimeStr = nowDateStr + ' ' + dinnerStartTime;
                        var dt = new Date(restTimeStr);
                        nowTimeSec = parseInt(dt.getTime() / 1000);
                        restSec += realNowTimeSec - nowTimeSec;
                    }
                    else if(nowTimeIntVal > eTimeIntVal) {
                        flag = false;
                    }

                    if (nowTimeIntVal > lunchEndIntVal && nowTimeIntVal < dinnerEndIntVal) {
                        restSec =  45 * 60;
                    }
                    else if (nowTimeIntVal > dinnerEndIntVal) {
                        restSec =  90 * 60;
                    }
                }
                else {
                    var lunchStartTime = '10:35:00',
                        dinnerStartTime = '18:20:00',
                        lunchStartIntVal = strToInt(lunchStartTime),
                        lunchEndIntVal = 112000,
                        dinnerStartIntVal = strToInt(dinnerStartTime),
                        dinnerEndIntVal = 192000;
                    if (nowTimeIntVal < sTimeIntVal) {
                        flag = false;
                    }
                    else if (nowTimeIntVal >= lunchStartIntVal && nowTimeIntVal < lunchEndIntVal) {
                        var restTimeStr = nowDateStr + ' ' + lunchStartTime;
                        var dt = new Date(restTimeStr);
                        nowTimeSec = parseInt(dt.getTime() / 1000);
                        restSec += realNowTimeSec - nowTimeSec;
                    }
                    else if(nowTimeIntVal >= dinnerStartIntVal && nowTimeIntVal < dinnerEndIntVal) {
                        var restTimeStr = nowDateStr + ' ' + dinnerStartTime;
                        var dt = new Date(restTimeStr);
                        nowTimeSec = parseInt(dt.getTime() / 1000);
                        restSec += realNowTimeSec - nowTimeSec;
                    }
                    else if(nowTimeIntVal > eTimeIntVal) {
                        flag = false;
                    }

                    if (nowTimeIntVal > lunchEndIntVal && nowTimeIntVal < dinnerEndIntVal) {
                        restSec =  45 * 60;
                    }
                    else if (nowTimeIntVal > dinnerEndIntVal) {
                        restSec =  90 * 60;
                    }
                }
                var res = 0;
                if(flag) {
                    var nh = parseInt((nowTimeSec - timeSec - restSec) / 360) / 10;
                    res = nh != 0 ? parseInt(total * 100 / nh) / 100 : 0;
                }
                return res;
            };
            var pTotal = so['p_current_1'] || 0;
            if (weekNum % 2 == 1) {
                pRate = calcRate(pTotal, '06:00:00', '14:30:00', 'p');
            }
            else {
                //data['pShift1StartTime'] = '14:30';
                //data['pShift1EndTime'] = '23:00';
                pRate = calcRate(pTotal, '14:30:00', '23:00:00', 'p');
            }

            var qTotal = so['q_current_1'] + so['q_current_2'];
            qRate = calcRate(qTotal, '06:00:00', '23:00:00', 'q') || 0;
            data['LineQRate'] = qRate + ' U/H';
            data['LinePRate'] = pRate + ' U/H';
        }
    });

});
